
#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import threading
import selectors
import socket
import logging,time

FORMAT = '%(asctime)s %(thread)s %(threadName)s %(message)s'
logging.basicConfig(level=logging.INFO,format=FORMAT,datefmt="%Y-%m-%d %H:%M:%S")

class HttpServer:
    def __init__(self,bind=('127.0.0.1',222)):
        self.server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.bind = bind
        self.selector = selectors.DefaultSelector()
        self.lock = threading.Lock()
    def start(self):
        self.server.bind(self.bind)
        self.server.listen()
        self.server.setblocking(False)
        self.selector.register(self.server,events=selectors.EVENT_READ,data=self.accept)
        while True:
            events = self.selector.select()
            for key,mask in events:
                key.data(key.fileobj)

    def accept(self,sock:socket.socket):
        newsock,addr = sock.accept()
        logging.info('接受了一个新的连接>>>{}'.format(addr))
        newsock.setblocking(False)
        self.selector.register(newsock,events=selectors.EVENT_READ,data=self.recv)

    def recv(self,newsocket:socket.socket):
        read = newsocket.recv(1024)
        if read:
            with open('index.html', mode='r', encoding='utf-8') as f:
                data = f.read()
            response_header = "HTTP/1.1 200 OK\r\n"  # \r\n是为了兼容windows的换行
            response_empty_line = "\r\n"  # 加一个空行
            response = ''.join([response_header,response_empty_line,data])
            response = bytes(response, 'utf8')

            newsocket.send(response)

            self.selector.unregister(newsocket)
            newsocket.close()

    def stop(self):
        self.server.close()

t = HttpServer()
t.start()
